const uuidv1 = require("uuid/v1");
const moment = require("moment");
const md5Hex = require('md5-hex');

export class StringUtils {
    /**获取随机字串 */
    static getGeneralId(key: string) {
        return md5Hex(key + moment().format('YYYYMMDDHmmss') + '_' + uuidv1());
    }

    static isValidStringByLength(str: string, mix: number, max: number) {
        if (!str || typeof (str) != 'string') return false;
        if (str.length < mix || (max > 0 && str.length > max)) return false;
        return true;
    }

    /**
     * 获取url参数拼接
     * @param obj 拼接对象
     * @param excludeNull 是否排除null或者""的key，默认false
     * @param encode 是否要对参数值urlencode,默认false
     */
    static getSortKeys(obj: any, excludeNull: boolean = false, encode: boolean = false): string {
        var keyList: Array<string> = [];
        for (var key in obj) {
            if (excludeNull && (obj[key] === null && obj[key] === "")) continue;
            keyList.push(key);
        }
        keyList.sort();
        var stringA = "";
        for (var i = 0; i < keyList.length - 1; i++) {
            let value = obj[keyList[i]];
            if (encode) value = encodeURIComponent(value);
            stringA += keyList[i] + "=" + value + "&";
        }
        let value = obj[keyList[i]];
        if (encode) value = encodeURIComponent(value);
        stringA += keyList[i] + "=" + value;
        return stringA;
    }
}